<?php

declare(strict_types=1);

namespace  App\Lib\CurlCli;

use Swlib\SaberGM;
use Swlib\Saber;
use Swlib\Http\Exception\RequestException;

class SaberNetwork
{
    protected $saber;

    
    /**
     * $options array http请求基本参数
     */
    public function __construct($config)
    {
        try {
            if (isset($config['base_uri'])) {
                $this->saber = Saber::create([
                    'base_uri' => $config['base_uri'],
                    'timeout' => $config['time_out'] ?? 10,
                    'use_pool' => true
                ]);
            } else {
                $this->saber = Saber::create([
                    'use_pool' => true,
                    'timeout' => 10,
                ]);
            }
        } catch (RequestException $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * $url string get请求的地址
     */
    public function get($url = '', $options = [])
    {
        try {
            $content = $this->saber->get($url, $options)->getBody();
            return ['errorCode' => 0, 'data' => (string)$content];
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }
    /**
     * $url string post请求的地址
     * $data array post请求的数据
     */
    public function post($url = '', $data = [], $options = [])
    {
        try {
            $content = $this->saber->post($url, $data, $options)->getBody();
            return ['errorCode' => 0, 'data' => (string)$content];
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }
}
